import PropTypes from "prop-types";
import { useLocation } from "react-router-dom";
import { Form, Input } from "antd-mobile";
import { useEffect } from "react";

const ItemBlk = (props) => {
  const location = useLocation();
  const searchParams = new URLSearchParams(location.search);
  const [form] = Form.useForm();

  useEffect(() => {
    let formData = [
      { name: "itemCode", value: props.data.itemCode },
      { name: "itemName", value: props.data.itemName },
      { name: "bookQty", value: props.data.bookQty ? props.data.bookQty : 0 },
      { name: "realQty", value: props.data.realQty },
    ];
    if (props.type === "OPEN") {
      formData.push({ name: "bookQty", value: props.data.bookQty });
    }
    form.setFields(formData);
  }, [props.data]);

  const handleValChange = (changedValues) => {
    if (changedValues.realQty || (typeof changedValues.realQty === 'string' && changedValues.realQty.length === 0)) {
      props.handleValChange(props.data.id, changedValues.realQty);
    }
  };

  const checkQty = async (_, value) => {
    if (isNaN(value) || (typeof value === "string" && value.length === 0)) {
      return Promise.reject("请输入数字");
    } else if (parseFloat(value) <= 0) {
      return Promise.reject(`数量须大于0`);
    }
    return Promise.resolve();
  };

  return (
    <>
      {/* 用于滚动到对应位置 */}
      <div id={props.data.id}></div>
      <Form form={form} mode="card" onValuesChange={handleValChange}>
        <Form.Item name="itemCode" label="物料编码">
          <Input readOnly />
        </Form.Item>
        <Form.Item name="itemName" label="物料名称">
          <Input readOnly />
        </Form.Item>
        {props.type === "OPEN" ? (
          <Form.Item name="bookQty" label="账面数量">
            <Input readOnly />
          </Form.Item>
        ) : null}
        <Form.Item
          name="realQty"
          label="实盘数量"
          rules={[
            {
              validator: (rule, value, callback) =>
                checkQty(rule, value, callback),
            },
          ]}
        >
          <Input
            placeholder="请扫码或输入"
            readOnly={searchParams.get("status") === "DONE"}
          />
        </Form.Item>
      </Form>
    </>
  );
};

ItemBlk.propTypes = {
  type: PropTypes.string,
  data: PropTypes.object,
  handleValChange: PropTypes.func
};

export default ItemBlk;
